package com.xuxin.queue.activity;

import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.xuxin.queue.R;
import com.xuxin.queue.adapter.QueueAdapter;
import com.xuxin.queue.base.BaseSpeakActivity;
import com.xuxin.queue.bean.PlayerBean;
import com.xuxin.queue.bean.QueueBean;
import com.xuxin.queue.contract.QueueContract;
import com.xuxin.queue.presenter.QueuePresenter;
import com.xuxin.queue.utils.ACache;
import com.xuxin.queue.utils.BaseUtils;
import com.xuxin.queue.view.QueuePopup;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

/**
 * Created by xu_xin
 * Created on 2021/6/15 0015
 * 呼叫页面
 */
public class QueueActivity extends BaseSpeakActivity implements QueueContract.View {
    private final QueueContract.Presenter presenter = new QueuePresenter(this);
    private final SimpleDateFormat sdf1 = TimeUtils.getSafeDateFormat("yyyy年MM月dd日");
    private final SimpleDateFormat sdf2 = TimeUtils.getSafeDateFormat("HH:mm:ss");
    private QueueAdapter myQueueAdapter;
    private ThreadUtils.Task<Long> task;
    private ThreadUtils.Task<Object> task2;
    private String URL;
    @BindView(R.id.queue_time_NYR)
    TextView queue_time_NYR;
    @BindView(R.id.queue_time_SFM)
    TextView queue_time_SFM;
    @BindView(R.id.queue_recycle)
    RecyclerView queue_recycle;
    @BindView(R.id.queue_version)
    TextView queue_version;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_queue);
    }

    @Override
    public void initView() {
        BaseUtils.init(queue_recycle);
        myQueueAdapter = new QueueAdapter();
        queue_recycle.setAdapter(myQueueAdapter);
        String version = "version_" + AppUtils.getAppVersionName();
        queue_version.setText(version);
        /**
         * 获取配置URL
         */
        URL = ACache.get(context).getAsString("URL");
    }

    private long timestamp;

    @Override
    public void initData() {
        /**
         * 时钟
         */
        ThreadUtils.executeBySingleAtFixRate(task = new ThreadUtils.Task<Long>() {
            @Override
            public Long doInBackground() throws Throwable {
                if (timestamp != 0) {
                    timestamp = timestamp + 1000;
                } else {
                    timestamp = System.currentTimeMillis();
                }
                return timestamp;
            }

            @Override
            public void onSuccess(Long result) {
                queue_time_NYR.setText(TimeUtils.millis2String(result, sdf1));
                queue_time_SFM.setText(TimeUtils.millis2String(result, sdf2));
            }

            @Override
            public void onCancel() {
                LogUtils.e("[时钟]任务取消");
            }

            @Override
            public void onFail(Throwable t) {
                LogUtils.e("[时钟]任务失败");
            }
        }, 1, TimeUnit.SECONDS);
        /**
         * 间隔查询排队
         */
        ThreadUtils.executeBySingleAtFixRate(task2 = new ThreadUtils.Task<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                return null;
            }

            @Override
            public void onSuccess(Object result) {
                mHandler.sendEmptyMessage(0);
            }

            @Override
            public void onCancel() {
                LogUtils.e("[间隔查询排队]任务取消");
            }

            @Override
            public void onFail(Throwable t) {
                LogUtils.e("[间隔查询排队]任务失败");
            }
        }, 10, TimeUnit.SECONDS);
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onClick(View view) {

    }

    int i = 0;
    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NotNull Message message) {
            if (message.what == 0) {
                if (!StringUtils.isEmpty(URL)) {
                    presenter.getQueuingInfo(URL);
                    presenter.getPlayer(URL);
                } else {
                    // ToastUtils.showShort("未配置URL");
                }
            } else if (message.what == 10) {
                if (null != basePopupView && basePopupView.isShow()) {
                    basePopupView.smartDismiss();
                }
            } else if (message.what == 101) {
                i++;
                LogUtils.e("i = " + i);
                showQueue("哈哈哈哈哈 " + i);
            }
            return false;
        }
    });

    @Override
    public void onSuccess(QueueBean queueBean) {
        myQueueAdapter.setNewInstance(queueBean.getResult());
    }


    @Override
    public void onSuccess(PlayerBean playerBean) {
        if (null != playerBean.getResult() &&
                !StringUtils.isEmpty(playerBean.getResult().getPatName()) &&
                !StringUtils.isEmpty(playerBean.getResult().getRoomName())) {
            String message = "请" + playerBean.getResult().getPatName() + "前往" + playerBean.getResult().getRoomName() + "就诊";
            LogUtils.e("message = " + message);
            try {
                showQueue(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                startAuto(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            /*showQueue("哈哈哈哈哈");
            mHandler.sendEmptyMessageDelayed(101, 1000);
            mHandler.sendEmptyMessageDelayed(101, 2000);
            mHandler.sendEmptyMessageDelayed(101, 3000);*/
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.showShort("再按一次退出");
                exitTime = System.currentTimeMillis();
            } else {
                ActivityUtils.finishAllActivities();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ThreadUtils.cancel(task, task2);
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (null != basePopupView) {
            basePopupView.dismiss();
            queuePopup = null;
            basePopupView = null;
        }
    }

    private QueuePopup queuePopup;
    private BasePopupView basePopupView;

    private void showQueue(String name) {
        if (null == queuePopup) {
            queuePopup = new QueuePopup(context, name);
        } else {
            queuePopup.setName(name);
        }
        if (null == basePopupView) {
            basePopupView = new XPopup.Builder(context).hasShadowBg(false).dismissOnTouchOutside(true).asCustom(queuePopup);
        }
        if (basePopupView.isShow()) {
            mHandler.removeMessages(10);
        }
        mHandler.sendEmptyMessageDelayed(10, 5000);
        basePopupView.show();
    }
}